package com.jandar.task;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.List;

import com.jandar.Resources;
import com.jandar.parser.IParser;
import com.jandar.table.config.Column;
import com.jandar.table.config.IdGeneratorInfo;
import com.jandar.table.config.Table;
import com.jandar.util.DBUtils;
import com.jandar.util.DateUtils;
import com.jandar.util.ExceptionUtils;
import com.jandar.util.SQLUtils;

/**
 * 建达用定时器任务。
 * 
 * @author pqj
 * @version 2009-7-8
 */
public class JandarTimerTask extends DefaultTimerTask {

	/** 建达交换表 */
	private Table table = null;

	public JandarTimerTask() {
		this.table = Resources.getInstance().getTableCfgMap().get(
				Resources.getInstance().getExchangeTable());
	}

	/**
	 * 结束处理。
	 * 
	 * @param jhrq 交换日期
	 * @param jhtable 交换表名
	 * @param fileName 导入文件名
	 * @param parser 解析器
	 */
	public void doLastWork(Date jhrq, String jhtable, String fileName, IParser parser) {
		// 交换条数
		int cnt = parser.getChangeCount();
		// 部门
		String depart = table.getDepartment().getTitle();

		// 插入交换记录
		Connection conn = null;
		Statement statement = null;
		try {
			List<Column> columns = table.getColumn();
			IdGeneratorInfo generator = SQLUtils.getIdGenerator(table.getId());
			String[] values = SQLUtils.createValues(generator, table.getIdCount(), 
					DateUtils.format(columns.get(0).getFormat(), jhrq), 
					jhtable, String.valueOf(cnt), depart, fileName);
			String insertSql = SQLUtils.createInsertSQL(Resources.getInstance().getExchangeTable(), values);
			logger.debug("插入交换表SQL: " + insertSql);
			conn = DBUtils.getInstance().getConnection();
			statement = conn.createStatement();
			statement.executeUpdate(insertSql);
		} catch (Exception e) {
			ExceptionUtils.error(e);
		} finally {
			try {
				DBUtils.closeStatement(statement);
			} catch (SQLException e) {
				ExceptionUtils.error(e);
			}

			try {
				DBUtils.closeConnection(conn);
			} catch (SQLException e) {
				ExceptionUtils.error(e);
			}
		}
	}
}